package com.lanou.web.controller;

import com.lanou.entity.Book;
import com.lanou.entity.PageInfo;
import com.lanou.service.BookService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
//@RequestMapping("/book") 窄化路径
public class BookController {
    @Resource//注入实体对象
    private BookService bookService;

    //显示所有图书
    @ResponseBody //返回json数据
    @RequestMapping("/list") //路径
    public PageInfo list(PageInfo pageInfo, String sort, String order) {
        return bookService.list(pageInfo, sort, order);
    }

    //添加图书
    @RequestMapping("/add")
    public Object add(Book book, @RequestParam("priImgFile") CommonsMultipartFile priImgFile,// @RequestParam("priImgFile")设定的参数指定为前端的priImgFile
                      @RequestParam("subImgFiles") CommonsMultipartFile[] subImgFiles, HttpServletRequest request) throws IOException {
        String priImgFileName = UUID.randomUUID().toString() + ".jpg";
        String priImg = "/static/img/" + priImgFileName;
        String priImgFileRealPath = request.getServletContext().getRealPath(priImg);
        IOUtils.copy(priImgFile.getInputStream(), new FileOutputStream(priImgFileRealPath));
        book.setPriImg(priImg);
        // 拼接字符串,把图片的地址用逗号分开
        String subImgs = "";
        for (CommonsMultipartFile subImgFile : subImgFiles) {
            String subImgFileName = UUID.randomUUID().toString() + ".jpg";
            String subImg = "/static/img/" + subImgFileName;
            String subImgFileRealPath = request.getServletContext().getRealPath(subImg);
            IOUtils.copy(subImgFile.getInputStream(), new FileOutputStream(subImgFileRealPath));
            subImgs += subImg;
            subImgs += ",";
        }
        subImgs = subImgs.substring(0, subImgs.length() - 1);
        book.setSubImgs(subImgs);
        bookService.add(book);
        return "redirect:/index.html";
    }

    //删除图书
    @ResponseBody
    @RequestMapping("/del")
    public int del(Book book) {
        int bid = book.getBid();
        return bookService.del(bid);
    }
}
